package com.ruoyi.system.controller;

import java.text.DecimalFormat;
import java.util.List;

import com.ruoyi.system.domain.QTelManyi;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.QZzltj;
import com.ruoyi.system.service.IQZzltjService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.nio.file.*;
import java.io.*;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.Control.Customer;
import com.ruoyi.system.Control.ExcelMergeCellHandler;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.QPingjia;
import com.ruoyi.system.service.IQPingjiaService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 工作量统计Controller
 *
 * @author ruoyi
 * @date 2024-06-24
 */
@Controller
@RequestMapping("/system/zzltj")
public class QZzltjController extends BaseController {
    private String prefix = "system/zzltj";

    static List<QZzltj > listExcel =  new ArrayList<QZzltj>();

    @Autowired
    private IQZzltjService qZzltjService;

    @RequiresPermissions("system:zzltj:view")
    @GetMapping()
    public String zzltj(ModelMap mmap  ) {

        mmap.put("startTime", "2024-9-20 00:00:00");
        mmap.put("endTime", "2024-9-21 23:59:59");
        return prefix + "/zzltj";
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    @CrossOrigin
    public String getAbsoluteFile(String filename) {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    public static String timeFormat(Object scound) {
        Double d = Double.parseDouble(scound.toString());
        Integer seconds = (int) Math.round(d);
        if (seconds <= 0) return "";
        int h = seconds / 3600;
         String h1 = (h >=10 )?(String.valueOf(h)):( '0'+String.valueOf(h)) ;
        int m = seconds % 3600 / 60;
        String m1 = (m >=10 )?(String.valueOf(m)):( '0'+String.valueOf(m)) ;
        int s = seconds % 60; //不足60的就是秒，够60就是分

        String s1 = (s >=10 )?(String.valueOf(s)):( '0'+String.valueOf(s)) ;
         return  h1 + ":" + m1 + ":" + s1 + "";
    }

    public String getSumhrzsc(  List<QZzltj> list)
    {
        float sum = 0.00000f ;
        for(int i=0; i < list.size(); i++ ){
            sum += Float.valueOf(list.get(i).getHrzsc());
        }
        return sum + "";
    }

    public String getSumhrwj(  List<QZzltj> list)
    {
        int sum = 0 ;
        for(int i=0; i < list.size(); i++ ){
            sum += Integer.valueOf(list.get(i).getHrwj());
        }
        return sum + "";
    }

    public String getSumhrjt(  List<QZzltj> list)
    {
        int sum = 0 ;
        for(int i=0; i < list.size(); i++ ){
            sum += Integer.valueOf(list.get(i).getHrjt());
        }
        return sum + "";
    }

    public String getSumhravetime(  List<QZzltj> list)
    {
        float sum = 0.00000f ;
        for(int i=0; i < list.size(); i++ ){
            sum += Float.valueOf(list.get(i).getHravetime());
        }
        return sum + "";
    }

    public String getSumwhzsc(  List<QZzltj> list)
    {
        float sum = 0.00000f ;
        for(int i=0; i < list.size(); i++ ){
            sum += Float.valueOf(list.get(i).getWhzsc());
        }
        return sum + "";
    }

    public String getSumwhavetime(  List<QZzltj> list)
    {
        float sum = 0.00000f ;
        for(int i=0; i < list.size(); i++ ){
            sum += Float.valueOf(list.get(i).getWhavetime());
        }
        return sum + "";
    }



        /**
         * 查询工作量统计列表
         */
        @RequiresPermissions("system:zzltj:list")
        @PostMapping("/list")
        @ResponseBody
        public TableDataInfo list (QZzltj qZzltj)
        {
            startPage();
            List<QZzltj> list = qZzltjService.selectQZzltjList(qZzltj);


            QZzltj gongji = new QZzltj();

            gongji.setZxname("共计");

            gongji.setHrjt(getSumhrjt(list)); //呼入接听
            gongji.setHrwj(getSumhrwj(list));  //呼入未接
            gongji.setHrzsc(getSumhrzsc(list));  //呼入总时长
            gongji.setHravetime(getSumhravetime(list));  //呼入平均时间
            gongji.setWhzsc(getSumwhzsc(list));  //外呼总时长
            gongji.setWhavetime(getSumwhavetime(list));  //外呼平均时长

            float sum = Float.valueOf(getSumhrjt(list));
            float wjt = Float.valueOf(getSumhrwj(list));
            float  jtlv = ((sum)/(sum+wjt));
            System.out.println( jtlv + "================================");
            gongji.setJtlv(String.valueOf(jtlv)  );

            list.add(gongji);

            List<QZzltj> listRes = new ArrayList<QZzltj>();
            for (int i = 0; i < list.size(); i++) {
                QZzltj tmp = new QZzltj();
                tmp = list.get(i);
                if (!tmp.getZxname().equals("共计")){
                    if (tmp.getJtlv() == null || tmp.getHrwj().equals("0")){
                        tmp.setJtlv("100%");
                    }else{
                        double num = Float.parseFloat(tmp.getJtlv())*100;
                        int result = (int) Math.round(num);
                        System.out.println(result); // 输出4
                        tmp.setJtlv(result+"%");
                    }
                }else{
                    double num = Float.parseFloat(tmp.getJtlv())*100;
                    double number = num;
                    DecimalFormat decimalFormat = new DecimalFormat("#.00");
                    String result = decimalFormat.format(number);
                    System.out.println(result);
                    tmp.setJtlv(result+"%");
                }



                tmp.setHrzsc(timeFormat(tmp.getHrzsc()));
                tmp.setHravetime(timeFormat(tmp.getHravetime()));
                if (Float.valueOf( tmp.getWhzsc() )  > 0.0000001f){
                    tmp.setWhzsc(timeFormat(tmp.getWhzsc()));

                }else{

                    tmp.setWhzsc("00:00:00");
                }

                if (Float.valueOf( tmp.getWhavetime() )  > 0.0000001f){
                    tmp.setWhavetime(timeFormat(tmp.getWhavetime()));

                }else{

                    tmp.setWhavetime("00:00:00");
                }
                listRes.add(tmp);
            }

            this.listExcel = listRes ;

            return getDataTable(listRes);
        }

        /**
         * 导出工作量统计列表
         */
        @RequiresPermissions("system:zzltj:export")
        @Log(title = "工作量统计", businessType = BusinessType.EXPORT)
        @PostMapping("/export")
        @ResponseBody
        public AjaxResult export (QZzltj qZzltj)
        {
           // List<QZzltj> data = qZzltjService.selectQZzltjList(qZzltj);

            List<QZzltj> data = this.listExcel ;


            String filename = new String("工作量统计(template)" + ".xlsx");


            Path sourcePath = Paths.get(getAbsoluteFile(filename));
            Path destinationPath = Paths.get(getAbsoluteFile("工作量统计.xlsx"));

            try {
                Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
                System.out.println("File copied successfully.");
            } catch (IOException e) {
                System.out.println("Error occurred while copying file.");
                e.printStackTrace();
            }

            try {
                FileInputStream file = new FileInputStream(getAbsoluteFile("工作量统计.xlsx"));
                Workbook workbook = WorkbookFactory.create(file);
                Sheet sheet = workbook.getSheetAt(0);
                int rowIndex = 3;  //从第三行开始写
                for (int i = 0; i < data.size(); i++) {
                    QZzltj tmp = new QZzltj();
                    tmp = (QZzltj) data.get(i);


                    Row row = sheet.getRow(i + rowIndex);
                    int colIndex = 0;
                    Cell cell = row.getCell(colIndex++);
                    cell.setCellValue(tmp.getZxname()); //坐席

                    cell = row.getCell(colIndex++);
                    cell.setCellValue(tmp.getHrjt());   //呼入接听

                    cell = row.getCell(colIndex++);
                    cell.setCellValue(tmp.getHrwj());   //呼入未接

                    cell = row.getCell(colIndex++);
                    cell.setCellValue(tmp.getJtlv());   //接听率

                    cell = row.getCell(colIndex++);
                    cell.setCellValue(tmp.getHrzsc());   //呼入总时长

                    cell = row.getCell(colIndex++);
                    cell.setCellValue(tmp.getHravetime());   //呼入平均时长

                    cell = row.getCell(colIndex++);
                    cell.setCellValue(tmp.getWhzsc());   //外呼总时长


                }
                Row row = sheet.getRow(1);
                Cell cell = row.getCell(3);
                // 修改单元格的内容
                cell.setCellValue("统计结束时间：" + qZzltj.getEndTime());

                row = sheet.getRow(1);
                cell = row.getCell(0);
                // 修改单元格的内容
                cell.setCellValue("统计开始时间：" + qZzltj.getStartTime());

                file.close();

                FileOutputStream outFile = new FileOutputStream(getAbsoluteFile("工作量统计.xlsx"));
                workbook.write(outFile);
                outFile.close();

                System.out.println("Excel file modified successfully.");

            } catch (Exception e) {
                e.printStackTrace();
            }

            return AjaxResult.success("工作量统计.xlsx");
        }

        /**
         * 新增工作量统计
         */
        @GetMapping("/add")
        public String add ()
        {
            return prefix + "/add";
        }

        /**
         * 新增保存工作量统计
         */
        @RequiresPermissions("system:zzltj:add")
        @Log(title = "工作量统计", businessType = BusinessType.INSERT)
        @PostMapping("/add")
        @ResponseBody
        public AjaxResult addSave (QZzltj qZzltj)
        {
            return toAjax(qZzltjService.insertQZzltj(qZzltj));
        }

        /**
         * 修改工作量统计
         */
        @RequiresPermissions("system:zzltj:edit")
        @GetMapping("/edit/{zxname}")
        public String edit (@PathVariable("zxname") String zxname, ModelMap mmap)
        {
            QZzltj qZzltj = qZzltjService.selectQZzltjByZxname(zxname);
            mmap.put("qZzltj", qZzltj);
            return prefix + "/edit";
        }

        /**
         * 修改保存工作量统计
         */
        @RequiresPermissions("system:zzltj:edit")
        @Log(title = "工作量统计", businessType = BusinessType.UPDATE)
        @PostMapping("/edit")
        @ResponseBody
        public AjaxResult editSave (QZzltj qZzltj)
        {
            return toAjax(qZzltjService.updateQZzltj(qZzltj));
        }

        /**
         * 删除工作量统计
         */
        @RequiresPermissions("system:zzltj:remove")
        @Log(title = "工作量统计", businessType = BusinessType.DELETE)
        @PostMapping("/remove")
        @ResponseBody
        public AjaxResult remove (String ids)
        {
            return toAjax(qZzltjService.deleteQZzltjByZxnames(ids));
        }
    }
